/**
作者：
 */
package com.zito.pojo;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.downlove.cache.CacheManager;
import com.downlove.common.Inflector;
import com.downlove.database.DBException;
import com.downlove.database.POJO;
import com.downlove.database.QueryHelper;
import com.downlove.database.SequenceManager;
import com.zito.bean.Electronicfiles;

public class ElectronicPOJO extends POJO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Object[] valueObj;
	private String __this_table_name;

	public long Save(String sessionid) {
		this.setId(SequenceManager.nextID(this.getClass().getSimpleName()));
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(_InsertSQL(this), this.valueObj);
			QueryHelper.commitUpdate((new Electronicfiles()).updateObject(),
					this.getId(), sessionid);
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				throw new DBException(e1);
			}
			throw new DBException(e);
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				throw new DBException(e2);
			}
		}
		if (this.IsObjectCachedByID())
			CacheManager.evict(CacheRegion(), OBJ_COUNT_CACHE_KEY);
		return flag ? this.getId() : -1;
	}

	public long Update(String sessionid) {
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit(); //开启事物
			QueryHelper.commitUpdate(//主表
					_updateSQL( "title", "content", "id"), this.valueObj);
			QueryHelper.commitUpdate((new Electronicfiles()).updateObject(),//附表
					this.getId(), sessionid);
			QueryHelper.commit();//以上两条语句都更新成功则提交
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();//三条更新语句其中发生错误，需要回滚
			} catch (SQLException e1) {
				throw new DBException(e1);
			}
			throw new DBException(e);
		} finally {
			try {
				QueryHelper.closeTransConnection();//关闭
			} catch (SQLException e2) {
				throw new DBException(e2);
			}
		}
		Evict(getId());
		return flag ? this.getId() : -1;
	}

	private String _updateSQL(String... args) {
		Map<String, Object> pojo_bean = this.ListInsertableFields();
		StringBuilder sql = new StringBuilder("UPDATE ");
		sql.append(TableName());
		sql.append(" SET ");
		valueObj = new Object[args.length];
		for (int i = 0; i < args.length - 1; i++) {
			if (i > 0)
				sql.append(',');
			sql.append(args[i] + "=?");
			valueObj[i] = pojo_bean.get(args[i]);
		}
		valueObj[args.length - 1] = pojo_bean.get(args[args.length - 1]);
		// sql.append(" WHERE " + args[args.length-1]
		// +"="+pojo_bean.get(args[args.length-1]));
		sql.append(" WHERE " + args[args.length - 1] + "=?");
		return sql.toString();
	}

	private String _InsertSQL(ElectronicPOJO obj) {
		Map<String, Object> pojo_bean = obj.ListInsertableFields();
		String[] fields = pojo_bean.keySet().toArray(
				new String[pojo_bean.size()]);
		StringBuilder sql = new StringBuilder("INSERT INTO ");
		sql.append(obj.TableName());
		sql.append('(');
		valueObj = new Object[fields.length];
		for (int i = 0; i < fields.length; i++) {
			if (i > 0)
				sql.append(',');
			sql.append(fields[i]);
		}
		sql.append(") VALUES(");
		for (int i = 0; i < fields.length; i++) {
			if (i > 0)
				sql.append(',');
			sql.append('?');
			valueObj[i] = pojo_bean.get(fields[i]);
		}
		sql.append(')');
		return sql.toString();
	}

	protected String TableName() {
		if (__this_table_name == null)
			__this_table_name = Inflector.getInstance().tableize(getClass());
		return __this_table_name;
	}

	/**
	 * 列出要插入到数据库的域集合，子类可以覆盖此方法
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String, Object> ListInsertableFields() {
		try {
			Map<String, Object> props = BeanUtils.describe(this);
			if (getId() <= 0)
				props.remove("id");
			props.remove("class");
			return props;
		} catch (Exception e) {
			throw new RuntimeException("Exception when Fetching fields of "
					+ this);
		}
	}

	public List<Long> idLimitFilter(String filter, int start, int end) {
		String sql = "SELECT id FROM " + TableName() + " WHERE " + filter
				+ " ORDER BY topic DESC, id DESC  LIMIT " + start + "," + end + "";
		return QueryHelper.queryList(sql);
	}

	public List<Long> idLimit(int start, int end) {
		String sql = "SELECT id FROM " + TableName()
				+ " ORDER BY topic DESC, id DESC  LIMIT " + start + "," + end + "";
		return QueryHelper.queryList(sql);
	}

	public int setTopic() {
		String sql = "UPDATE " + TableName() + " SET topic=1 WHERE id="
				+ getId();
		//System.out.println("setTopic :"+ sql);
		int tmp = QueryHelper.update(sql);
		Evict(getId());
		return tmp;
	}
	
	public int unTopic() {
		String sql = "UPDATE " + TableName() + " SET topic=0 WHERE id="
				+ getId();
		//System.out.println("unTopic :"+ sql);
		int tmp = QueryHelper.update(sql);
		Evict(getId());
		return tmp;
	}
	
	
	public List<Long> idListFilter(String filter, int page, int size) {
		String sql = "SELECT id FROM " + TableName() + " WHERE " + filter
				+ " ORDER BY topic DESC, id DESC";
		return QueryHelper.queryList(sql, page, size);
	}
	
	public List<Long> idListFilterByID(String filter, int page, int size) {
		String sql = "SELECT id FROM " + TableName() + " WHERE " + filter
				+ " ORDER BY id DESC";
		return QueryHelper.queryList(sql, page, size);
	}
}
